package com.zhijian.medical.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.zhijian.medical.dao.local.NgsSjfxMapper;
import com.zhijian.medical.entity.dto.NgsSjfxDto;
import com.zhijian.medical.entity.po.ExperimentProcessSampleLog;
import com.zhijian.medical.entity.po.Ngs;
import com.zhijian.medical.entity.po.NgsSjfx;
import com.zhijian.medical.entity.vo.request.ExperimentProcessSampleSearchVo;
import com.zhijian.medical.entity.vo.request.NgsSjfxSaveOrUpdateVo;
import com.zhijian.medical.entity.vo.request.NgsSjfxSearchVo;
import com.zhijian.medical.entity.vo.response.ExperimentProcessSampleVo;
import com.zhijian.medical.entity.vo.response.NgsSjfxVo;
import com.zhijian.medical.enums.AllExperimentationStepStatusEnum;
import com.zhijian.medical.enums.ExperimentTypeEnum;
import com.zhijian.medical.enums.NgsStatusEnum;
import com.zhijian.medical.enums.StatusEnum;
import com.zhijian.medical.holder.CurrentUserHolder;
import com.zhijian.medical.service.ExperimentProcessSampleLogService;
import com.zhijian.medical.service.ExperimentProcessSampleService;
import com.zhijian.medical.service.NgsService;
import com.zhijian.medical.service.NgsSjfxService;
import com.zhijian.medical.util.AssertUtil;
import com.zhijian.medical.util.JsonUtil;
import com.zhijian.medical.util.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 二代测序-数据分析（测序室、数据室） 业务处理层
 *
 * @author HCG
 * @version: 1.0
 * @date 2022-08-24 15:58:57
 */
@Slf4j
@Service
public class NgsSjfxServiceImpl implements NgsSjfxService {

    @Autowired
    private NgsSjfxMapper mapper;

    @Autowired
    private NgsService ngsService;

    @Autowired
    private ExperimentProcessSampleService experimentProcessSampleService;

    @Autowired
    private ExperimentProcessSampleLogService experimentProcessSampleLogService;

    @Override
    public NgsSjfx selectById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public NgsSjfx selectByNgsId(Long ngsId) {
        return mapper.selectByNgsId(ngsId);
    }

    @Override
    public NgsSjfxVo selectVoById(Long id) {
        return mapper.selectVoById(id);
    }

    @Override
    public NgsSjfxVo selectVoByNgsId(Long ngsId) {
        NgsSjfxVo ngsSjfxVo = mapper.selectVoByNgsId(ngsId);
        if (Objects.isNull(ngsSjfxVo)) {
            return null;
        }
        Ngs ngs = ngsService.selectById(ngsId);
        if (Objects.isNull(ngs)) {
            return null;
        }
        ngsSjfxVo.setResult(ngs.getStatus() > NgsStatusEnum.SJFX.getCode().byteValue() ?
                AllExperimentationStepStatusEnum.END.getCode().byteValue() : AllExperimentationStepStatusEnum.UN_END.getCode().byteValue());
        ngsSjfxVo.setResultStr(ngs.getStatus() > NgsStatusEnum.SJFX.getCode().byteValue() ?
                AllExperimentationStepStatusEnum.END.getDesc() : AllExperimentationStepStatusEnum.UN_END.getDesc());
        String data = ngsSjfxVo.getData();
        if (StringUtils.isNotBlank(data)) {
            ngsSjfxVo.setDataList(JsonUtil.toArray(data, NgsSjfxDto.class));
        }
        return ngsSjfxVo;
    }

    @Override
    public void deleteById(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public void deleteByNgsId(Long ngsId) {
        mapper.deleteByNgsId(ngsId);
    }

    @Override
    public Long insert(NgsSjfx ngsSjfx) {
        Date now = new Date();
        ngsSjfx.setCreateTime(now);
        ngsSjfx.setUpdateTime(now);
        ngsSjfx.setSysxfxfwqdcxy(StatusEnum.UN_NORMAL.getCode().byteValue());
        ngsSjfx.setJfxhdcx(StatusEnum.UN_NORMAL.getCode().byteValue());
        ngsSjfx.setHeqpgd(StatusEnum.UN_NORMAL.getCode().byteValue());
        ngsSjfx.setPdfxtgd(StatusEnum.UN_NORMAL.getCode().byteValue());
        return mapper.insert(ngsSjfx) > 0 ? ngsSjfx.getId() : 0L;
    }

    @Override
    public boolean update(NgsSjfx ngsSjfx) {
        Date now = new Date();
        ngsSjfx.setUpdateTime(now);
        return mapper.updateByPrimaryKey(ngsSjfx) != 0;
    }

    @Override
    public Integer count(NgsSjfxSearchVo ngsSjfxSearchVo) {
        return mapper.count(ngsSjfxSearchVo);
    }

    @Override
    public List<NgsSjfxVo> selectList(NgsSjfxSearchVo ngsSjfxSearchVo) {
        return mapper.selectList(ngsSjfxSearchVo);
    }

    @Override
    public Page<NgsSjfxVo> selectPage(NgsSjfxSearchVo ngsSjfxSearchVo) {
        //先直接查总数
        int count = count(ngsSjfxSearchVo);
        //分页
        Page<NgsSjfxVo> page = new Page<>(true, count, ngsSjfxSearchVo.getPageNum(), ngsSjfxSearchVo.getPageSize());
        ngsSjfxSearchVo.setStartIndex(page.getStartIndex());
        page.setPage(true);
        page.setTotalCount(count);
        List<NgsSjfxVo> responseVos = this.selectList(ngsSjfxSearchVo);
        page.setData(responseVos);
        return page;
    }

    @Transactional(rollbackFor = Exception.class, value = "localTransactionManager")
    @Override
    public boolean saveOrUpdate(NgsSjfxSaveOrUpdateVo ngsSjfxSaveOrUpdateVo) {
        Long ngsId = ngsSjfxSaveOrUpdateVo.getNgsId();
        Ngs ngs = ngsService.selectById(ngsId);
        AssertUtil.notNull(ngs, "此实验不存在或者已被删除");
        Ngs updateParam = Ngs.builder()
                .id(ngsId)
                .endTime(new Date())
                .build();
        if (ngs.getStatus() < NgsStatusEnum.END.getCode().byteValue()) {
            //修改实验的状态
            updateParam.setStatus(NgsStatusEnum.END.getCode().byteValue());
        }
        ngsService.updateByPrimaryKeySelective(updateParam);
        List<NgsSjfxDto> dataList = ngsSjfxSaveOrUpdateVo.getDataList();
        if (CollectionUtil.isNotEmpty(dataList)) {
            ngsSjfxSaveOrUpdateVo.setData(JsonUtil.toString(dataList));
        }
        NgsSjfx dbParam = new NgsSjfx();
        BeanUtils.copyProperties(ngsSjfxSaveOrUpdateVo, dbParam);

        NgsSjfx oldNgsSjfx = this.selectByNgsId(ngsId);
        if (Objects.isNull(oldNgsSjfx)) {
            this.insert(dbParam);
        } else {
            dbParam.setId(oldNgsSjfx.getId());
            this.update(dbParam);
        }
        List<ExperimentProcessSampleVo> experimentProcessSampleVos = experimentProcessSampleService.selectList(ExperimentProcessSampleSearchVo.builder()
                .mainType(ExperimentTypeEnum.NGS.getCode().byteValue())
                .experimentProcessId(ngsId)
                .build());
        //保存样本日志
        experimentProcessSampleLogService.saveBatch(experimentProcessSampleVos.stream().map(e -> ExperimentProcessSampleLog.builder()
                .sampleId(e.getId())
                .fishId(ngsId)
                .mainType(ExperimentTypeEnum.NGS.getCode().byteValue())
                .op(String.format("%s%s-%s", ngs.getName(), ngs.getProcessNumber(), NgsStatusEnum.SJFX.getDesc()))
                .opUser(CurrentUserHolder.getUser().getName())
                .build()).collect(Collectors.toList()));
        return true;
    }

}